<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--部门数据-->
      <el-col :span="4" :xs="24">
        <div class="head-container">
          <el-input
            v-model="companyName"
            placeholder="请输入公司名称"
            clearable
            size="small"
            prefix-icon="el-icon-search"
            style="margin-bottom: 20px"
          />
        </div>
        <div class="head-container">
          <el-tree
            :data="filteredData"
            :props="defaultProps"
            :expand-on-click-node="false"
            ref="tree"
            node-key="companyId"
            default-expand-all
            highlight-current
            @node-click="handleNodeClick"
          />
        </div>
      </el-col>
      <el-col :span="20" :xs="24">
        <!--        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"-->
        <!--                 label-width="68px">-->
        <!--          &lt;!&ndash;      <el-form-item label="公司dept" prop="companDept">&ndash;&gt;-->
        <!--          &lt;!&ndash;        <el-input&ndash;&gt;-->
        <!--          &lt;!&ndash;          v-model="queryParams.companDept"&ndash;&gt;-->
        <!--          &lt;!&ndash;          placeholder="请输入公司dept"&ndash;&gt;-->
        <!--          &lt;!&ndash;          clearable&ndash;&gt;-->
        <!--          &lt;!&ndash;          @keyup.enter.native="handleQuery"&ndash;&gt;-->
        <!--          &lt;!&ndash;        />&ndash;&gt;-->
        <!--          &lt;!&ndash;      </el-form-item>&ndash;&gt;-->
        <!--          <el-form-item label="公司法人" prop="legalPerson">-->
        <!--            <el-input-->
        <!--              v-model="queryParams.legalPerson"-->
        <!--              placeholder="请输入公司法人"-->
        <!--              clearable-->
        <!--              @keyup.enter.native="handleQuery"-->
        <!--            />-->
        <!--          </el-form-item>-->
        <!--          &lt;!&ndash;      <el-form-item label="公司钱包id编号" prop="walletCompanyId">&ndash;&gt;-->
        <!--          &lt;!&ndash;        <el-input&ndash;&gt;-->
        <!--          &lt;!&ndash;          v-model="queryParams.walletCompanyId"&ndash;&gt;-->
        <!--          &lt;!&ndash;          placeholder="请输入公司钱包id编号"&ndash;&gt;-->
        <!--          &lt;!&ndash;          clearable&ndash;&gt;-->
        <!--          &lt;!&ndash;          @keyup.enter.native="handleQuery"&ndash;&gt;-->
        <!--          &lt;!&ndash;        />&ndash;&gt;-->
        <!--          &lt;!&ndash;      </el-form-item>&ndash;&gt;-->
        <!--          <el-form-item label="公司名称" prop="companyName">-->
        <!--            <el-input-->
        <!--              v-model="queryParams.companyName"-->
        <!--              placeholder="请输入公司名称"-->
        <!--              clearable-->
        <!--              @keyup.enter.native="handleQuery"-->
        <!--            />-->
        <!--          </el-form-item>-->
        <!--          <el-form-item label="信用代码" prop="companyCode">-->
        <!--            <el-input-->
        <!--              v-model="queryParams.companyCode"-->
        <!--              placeholder="请输入公司信用代码"-->
        <!--              clearable-->
        <!--              @keyup.enter.native="handleQuery"-->
        <!--            />-->
        <!--          </el-form-item>-->
        <!--          <el-form-item label="联系电话" prop="companyPhone">-->
        <!--            <el-input-->
        <!--              v-model="queryParams.companyPhone"-->
        <!--              placeholder="请输入公司联系电话"-->
        <!--              clearable-->
        <!--              @keyup.enter.native="handleQuery"-->
        <!--            />-->
        <!--          </el-form-item>-->
        <!--          <el-form-item label="公司别名" prop="companyNick">-->
        <!--            <el-input-->
        <!--              v-model="queryParams.companyNick"-->
        <!--              placeholder="请输入公司别名"-->
        <!--              clearable-->
        <!--              @keyup.enter.native="handleQuery"-->
        <!--            />-->
        <!--          </el-form-item>-->
        <!--          <el-form-item label="纳税人识别号" prop="registrationNumber">-->
        <!--            <el-input-->
        <!--              v-model="queryParams.registrationNumber"-->
        <!--              placeholder="请输入公司纳税人识别号"-->
        <!--              clearable-->
        <!--              @keyup.enter.native="handleQuery"-->
        <!--            />-->
        <!--          </el-form-item>-->
        <!--          <el-form-item label="公司税号" prop="taxNumber">-->
        <!--            <el-input-->
        <!--              v-model="queryParams.taxNumber"-->
        <!--              placeholder="请输入公司税号"-->
        <!--              clearable-->
        <!--              @keyup.enter.native="handleQuery"-->
        <!--            />-->
        <!--          </el-form-item>-->
        <!--          <el-form-item label="省市区">-->
        <!--            <el-cascader v-model="queryParams.area" :options="provinceOptions" @change="SeachLocationChange"-->
        <!--                         prop="stationArea" placeholder="请选择区县"/>-->
        <!--          </el-form-item>-->
        <!--          &lt;!&ndash;                <el-form-item label="所属省份" prop="province">-->
        <!--                            <el-input-->
        <!--                              v-model="queryParams.province"-->
        <!--                              placeholder="请输入公司所属省份"-->
        <!--                              clearable-->
        <!--                              @keyup.enter.native="handleQuery"-->
        <!--                            />-->
        <!--                          </el-form-item>-->
        <!--                          <el-form-item label="所市" prop="city">-->
        <!--                            <el-input-->
        <!--                              v-model="queryParams.city"-->
        <!--                              placeholder="请输入公司所属市"-->
        <!--                              clearable-->
        <!--                              @keyup.enter.native="handleQuery"-->
        <!--                            />-->
        <!--                          </el-form-item>-->
        <!--                          <el-form-item label="所属区县" prop="area">-->
        <!--                            <el-input-->
        <!--                              v-model="queryParams.area"-->
        <!--                              placeholder="请输入公司所区县"-->
        <!--                              clearable-->
        <!--                              @keyup.enter.native="handleQuery"-->
        <!--                            />-->
        <!--                          </el-form-item>&ndash;&gt;-->
        <!--          <el-form-item label="详细地址" prop="address">-->
        <!--            <el-input-->
        <!--              v-model="queryParams.address"-->
        <!--              placeholder="请输入公司所属详细地址"-->
        <!--              clearable-->
        <!--              @keyup.enter.native="handleQuery"-->
        <!--            />-->
        <!--          </el-form-item>-->
        <!--          <el-form-item label="加注单价(元)" prop="unitPrice">-->
        <!--            <el-input-->
        <!--              v-model="queryParams.unitPrice"-->
        <!--              placeholder="请输入公司加注单价(元)"-->
        <!--              clearable-->
        <!--              @keyup.enter.native="handleQuery"-->
        <!--            />-->
        <!--          </el-form-item>-->
        <!--          <el-form-item>-->
        <!--            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>-->
        <!--            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>-->
        <!--          </el-form-item>-->
        <!--        </el-form>-->

        <!--    <el-row :gutter="10" class="mb8">
              <el-col :span="1.5">
                <el-button
                  type="primary"
                  plain
                  icon="el-icon-plus"
                  size="mini"
                  @click="handleAdd"
                  v-hasPermi="['consumer:company:add']"
                >新增
                </el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button
                  type="success"
                  plain
                  icon="el-icon-edit"
                  size="mini"
                  :disabled="single"
                  @click="handleUpdate"
                  v-hasPermi="['consumer:company:edit']"
                >修改
                </el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button
                  type="danger"
                  plain
                  icon="el-icon-delete"
                  size="mini"
                  :disabled="multiple"
                  @click="handleDelete"
                  v-hasPermi="['consumer:company:remove']"
                >删除
                </el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button
                  type="warning"
                  plain
                  icon="el-icon-download"
                  size="mini"
                  @click="handleExport"
                  v-hasPermi="['consumer:company:export']"
                >导出
                </el-button>
              </el-col>
              <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
            </el-row> -->

        <el-table v-loading="loading" :data="filteredStationList" @selection-change="handleSelectionChange">
          <!--          <el-table-column type="selection" width="55" align="center"/>-->
          <!--      <el-table-column label="公司id编号" align="center" prop="companyId" />-->
          <!--      <el-table-column label="公司dept" align="center" prop="companDept" />-->
          <el-table-column label="公司法人" align="center" prop="legalPerson"/>
          <el-table-column label="公司名称" align="center" prop="companyName"/>
          <el-table-column label="信用代码" align="center" prop="companyCode"/>
          <el-table-column label="联系电话" align="center" prop="companyPhone"/>
          <el-table-column label="公司别名" align="center" prop="companyNick"/>
          <el-table-column label="营业执照" align="center" prop="businessLicenseimg" width="100">
            <template slot-scope="scope">
              <image-preview :src="scope.row.businessLicenseimg" :width="50" :height="50"/>
            </template>
          </el-table-column>
          <el-table-column label="公司logo" align="center" prop="companyLogo" width="100">
            <template slot-scope="scope">
              <image-preview :src="scope.row.companyLogo" :width="50" :height="50"/>
            </template>
          </el-table-column>
          <el-table-column label="纳税人识别号" align="center" prop="registrationNumber"/>
          <el-table-column label="税号" align="center" prop="taxNumber"/>
          <el-table-column label="所属省份" align="center" prop="province"/>
          <el-table-column label="所属市" align="center" prop="city"/>
          <el-table-column label="所属区县" align="center" prop="area"/>
          <el-table-column label="详细地址" align="center" prop="address"/>
          <el-table-column label="加注单价(元)" align="center" prop="unitPrice">
            <template slot-scope="scope">
              {{ fentoyuan(scope.row.unitPrice) }}
            </template>
          </el-table-column>
          <!--      <el-table-column label="是否删除" align="center" prop="isDelete" />-->
          <!--      <el-table-column label="状态，0：正常，1：禁用" align="center" prop="status" />-->
          <el-table-column fixed="right" label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['consumer:company:edit']"
              >修改
              </el-button>
              <!--              <el-button-->
              <!--                size="mini"-->
              <!--                type="text"-->
              <!--                icon="el-icon-delete"-->
              <!--                @click="handleDelete(scope.row)"-->
              <!--                v-hasPermi="['consumer:company:remove']"-->
              <!--              >删除-->
              <!--              </el-button>-->
            </template>
          </el-table-column>
        </el-table>

        <Wallet v-if="selectedCompanyId!=null" :exampleProp="selectedCompanyId"></Wallet>
        <DealCompany v-if="selectedCompanyId!=null" :exampleProp="selectedCompanyId"></DealCompany>
      </el-col>
    </el-row>


    <!-- 添加或修改公司对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <!--        <el-form-item label="公司dept" prop="companDept">-->
        <!--          <el-input v-model="form.companDept" placeholder="请输入公司dept" />-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="公司法人" prop="legalPerson">-->
        <!--          <el-input v-model="form.legalPerson" placeholder="请输入公司法人" />-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="公司钱包id编号" prop="walletCompanyId">-->
        <!--          <el-input v-model="form.walletCompanyId" placeholder="请输入公司钱包id编号" />-->
        <!--        </el-form-item>-->
        <el-form-item label="公司名称" prop="companyName">
          <el-input v-model="form.companyName" placeholder="请输入公司名称"/>
        </el-form-item>
        <el-form-item label="信用代码" prop="companyCode">
          <el-input v-model="form.companyCode" placeholder="请输入公司信用代码"/>
        </el-form-item>
        <el-form-item label="联系电话" prop="companyPhone">
          <el-input v-model="form.companyPhone" placeholder="请输入公司联系电话"/>
        </el-form-item>
        <el-form-item label="公司别名" prop="companyNick">
          <el-input v-model="form.companyNick" placeholder="请输入公司别名"/>
        </el-form-item>
        <el-form-item label="营业执照" prop="businessLicenseimg">
          <image-upload v-model="form.businessLicenseimg"/>
        </el-form-item>
        <el-form-item label="公司logo" prop="companyLogo">
          <image-upload v-model="form.companyLogo"/>
        </el-form-item>
        <el-form-item label="纳税人识别号" prop="registrationNumber">
          <el-input v-model="form.registrationNumber" placeholder="请输入公司纳税人识别号"
                    :disabled="registrationNumber == null || registrationNumber == 0 || registrationNumber == '' ? false : true"/>
        </el-form-item>
        <el-form-item label="公司税号" prop="taxNumber">
          <el-input v-model="form.taxNumber" placeholder="请输入公司税号"/>
        </el-form-item>
        <el-form-item label="省市区">
          <el-cascader v-model="form.area" :options="provinceOptions" @change="handleLocationChange"
                       placeholder="请选择区县"/>
        </el-form-item>
        <!--        <el-form-item label="公司所属省份" prop="province">-->
        <!--          <el-input v-model="form.province" placeholder="请输入公司所属省份" />-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="公司所市" prop="city">-->
        <!--          <el-input v-model="form.city" placeholder="请输入公司所市" />-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="公司所区县" prop="area">-->
        <!--          <el-input v-model="form.area" placeholder="请输入公司所区县" />-->
        <!--        </el-form-item>-->
        <el-form-item label="详细地址" prop="address">
          <el-input v-model="form.address" placeholder="请输入公司所属详细地址"/>
        </el-form-item>
        <el-form-item label="加注单价(元)" prop="unitPrice" v-has-role="['dragon', 'admin']">
          <el-input v-model="unitPrice" placeholder="请输入公司加注单价(元)" @blur="handleBlurUnitVip"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {listCompany, getCompany, delCompany, addCompany, updateCompany} from "@/api/consumer/company";
import Wallet from "@/views/consumer/walletCompany/index";
import DealCompany from "@/views/consumer/dealCompany/index";
import provinceData from '@/store/data';
import {fenToYuan} from "@/utils/unitUtil";
import unitPrice from "@/views/consumer/unitPrice/index.vue";

export default {
  name: "Company",
  components: {
    Wallet,
    DealCompany
  },
  computed: {
    unitPrice() {
      return unitPrice
    },
    filteredStationList() {
      if (this.selectedCompanyId === null) {
        // 如果没有选中的companyId，则返回空数组
        return [];
      } else {
        // 使用过滤条件来过滤数据
        return this.companyList.filter((item) => item.companyId === this.selectedCompanyId);
      }

    },
    // 根据deptName过滤数据
    filteredData() {
      const keyword = this.companyName.trim().toLowerCase(); // 获取搜索关键字并去除首尾空格并转为小写
      if (!keyword) {
        // 如果关键字为空，返回原始数据
        return this.companyTreeData;
      }

      // 使用过滤条件来过滤数据
      const filteredData = [];
      this.companyTreeData.forEach((group) => {
        const children = group.children.filter((item) => {
          // 过滤条件：如果companyName包含关键字，则保留
          return item.label.toLowerCase().includes(keyword);
        });
        if (children.length > 0) {
          filteredData.push({...group, children});
        }
      });
      return filteredData;
    },
    // 根据companyName分组数据
    companyTreeData() {
      const groupedData = {};
      this.companyList.forEach((item) => {
        const companyName = item.companyName;
        if (!groupedData[companyName]) {
          groupedData[companyName] = [];
        }
        groupedData[companyName].push({
          label: item.companyName,
          companyId: item.companyId,
        });
      });

      // 将分组后的数据转换成树状结构
      const treeData = [];
      for (const companyName in groupedData) {
        treeData.push({
          label: companyName,
          children: groupedData[companyName],
        });
      }

      return treeData;
    },
  },
  data() {
    return {
      defaultProps: {
        children: 'companyName',
        label: 'label'
      },
      companyName: '', // 输入框的值
      selectedCompanyId: null, // 用于存储当前选中的公司的companyId

      // 纳税人识别号
      registrationNumber: null,

      // 地区数据
      provinceOptions: provinceData.map(item => ({
        value: item.name,
        label: item.name,
        children: item.city.map(city => ({
          value: city.name,
          label: city.name,
          children: city.area.map(area => ({
            value: area,
            label: area,
          })),
        })),
      })),
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 公司表格数据
      companyList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 100,
        companDept: null,
        legalPerson: null,
        walletCompanyId: null,
        companyName: null,
        companyCode: null,
        companyPhone: null,
        companyNick: null,
        businessLicenseimg: null,
        companyLogo: null,
        registrationNumber: null,
        taxNumber: null,
        province: null,
        city: null,
        area: null,
        address: null,
        unitPrice: null,
        isDelete: null,
        status: null
      },
      unitPrice: null,
      // 表单参数
      form: {
        pageNum: 1,
        pageSize: 10,
        companDept: null,
        legalPerson: null,
        walletCompanyId: null,
        companyName: null,
        companyCode: null,
        companyPhone: null,
        companyNick: null,
        businessLicenseimg: null,
        companyLogo: null,
        registrationNumber: null,
        taxNumber: null,
        province: null,
        city: null,
        area: null,
        address: null,
        unitPrice: null,
        isDelete: null,
        status: null
      },
      // 表单校验
      rules: {
        companDept: [
          {required: true, message: "公司dept不能为空", trigger: "blur"}
        ],
        isDelete: [
          {required: true, message: "是否删除不能为空", trigger: "blur"}
        ],
        status: [
          {required: true, message: "状态，0：正常，1：禁用不能为空", trigger: "change"}
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 分转元 */
    fentoyuan(fen) {
      return fenToYuan(fen);
    },
    // 单价移开时处理
    handleBlurUnitVip() {
      this.form.unitPrice = Math.round(this.unitPrice * 100);
    },
    handleNodeClick(node) {
      const companyId = node.children[0].companyId;
      console.log("node", companyId); // 正确输出companyId

      // 更新selectedCompanyId的值
      this.selectedCompanyId = companyId;
    },
    /** 选择地区 **/
    SeachLocationChange(value) {
      if (value.length > 0) {
        this.queryParams.province = value[0];
      }
      if (value.length > 1) {
        this.queryParams.city = value[1];
      }
      if (value.length > 2) {
        this.queryParams.area = value[2];
      }
    },
    /** 选择地区*/
    handleLocationChange(value) {
      if (value.length > 0) {
        this.form.province = value[0];
      }
      if (value.length > 1) {
        this.form.city = value[1];
      }
      if (value.length > 2) {
        this.form.area = value[2];
      }
      console.log("form：" + form);

    },
    /** 查询公司列表 */
    getList() {
      this.loading = true;
      listCompany(this.queryParams).then(response => {
        this.companyList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        companyId: null,
        companDept: null,
        legalPerson: null,
        walletCompanyId: null,
        companyName: null,
        companyCode: null,
        companyPhone: null,
        companyNick: null,
        businessLicenseimg: null,
        companyLogo: null,
        registrationNumber: null,
        taxNumber: null,
        province: null,
        city: null,
        area: null,
        address: null,
        unitPrice: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        isDelete: null,
        status: null
      };
      this.registrationNumber = null;
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams = {
        companDept: null,
        legalPerson: null,
        walletCompanyId: null,
        companyName: null,
        companyCode: null,
        companyPhone: null,
        companyNick: null,
        businessLicenseimg: null,
        companyLogo: null,
        registrationNumber: null,
        taxNumber: null,
        province: null,
        city: null,
        area: null,
        address: null,
        unitPrice: null,
        isDelete: null,
        status: null
      }
      this.registrationNumber = null;
      this.selectedCompanyId = null;
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.companyId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加公司";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const companyId = row.companyId || this.ids
      getCompany(companyId).then(response => {
        this.form = response.data;
        this.registrationNumber = this.form.registrationNumber;
        this.unitPrice = fenToYuan(this.form.unitPrice);
        this.open = true;
        this.title = "修改公司";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        console.log(this.registrationNumber)

        if (valid) {
          if (this.form.companyId != null) {
            if (this.registrationNumber == null || this.registrationNumber == 0 || this.registrationNumber == '') {
              //3为第一次修改
              this.form.status = 3;
              console.log("第一次修改");
            }
            updateCompany(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addCompany(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const companyIds = row.companyId || this.ids;
      this.$modal.confirm('是否确认删除公司编号为"' + companyIds + '"的数据项？').then(function () {
        return delCompany(companyIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('consumer/company/export', {
        ...this.queryParams
      }, `company_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
